﻿from PySide2.QtCore import *
from PySide2.QtWidgets import *
from PySide2.QtUiTools import *
from text_edit import *
from search_window_ui import *
from plugin_manager_ui import *
from prefrences_ui import *
import sys

class TabWidgetInfo:
    file = None
    codec = None
    textEdit = None

class MainAppUI(QObject):
    version = "1.0.0.0"

    ui = None
    findui = None
    pluginmgrui = None
    prefrencesui = None
    menuPlugins = None

    tabWidgets = { }
    codecInfo = { }

    def __init__(self):
        super(MainAppUI, self).__init__()

        qApp.mainApp = self

        uifile = QFile("MainApp.ui")
        if not uifile.open(QIODevice.ReadOnly):
            sys.exit(1)
        uiloader = QUiLoader()        
        self.ui = uiloader.load(uifile)
        if self.ui == None:
            sys.exit(2)
        uifile.close()

        self.ui.installEventFilter(self)

        self.findui = SearchWindow(self.ui)
        self.prefrencesui = Prefrences(self.ui)

        self.mapUi()
        self.pluginmgrui = PluginManager(self)
        self.ui.show()

    def mapUi(self):
        self.menubar = self.ui.findChild(QMenuBar, "menubar")
        self.toolBar = self.ui.findChild(QToolBar, "toolBar")        
        self.statusbar = self.ui.findChild(QStatusBar, "statusbar")

        self.mainTab = self.ui.findChild(QTabWidget, "tabWidget")

        self.actionOpen = self.ui.findChild(QAction, "actionOpen")
        self.actionSave = self.ui.findChild(QAction, "actionSave")
        self.actionSaveAll = self.ui.findChild(QAction, "actionSave_All")
        self.actionCloseAll = self.ui.findChild(QAction, "actionClose_All")
        self.actionUpdate = self.ui.findChild(QAction, "actionUpdate")

        self.actionCopy = self.ui.findChild(QAction, "actionCopy")
        self.actionPaste = self.ui.findChild(QAction, "actionPaste")
        self.actionDelete = self.ui.findChild(QAction, "actionDelete")
        self.actionSelectAll = self.ui.findChild(QAction, "actionSelect_All")
        self.actionCut = self.ui.findChild(QAction, "actionCut")

        self.actionExit = self.ui.findChild(QAction, "actionExit")
        self.actionNew = self.ui.findChild(QAction, "actionNew")
        self.menuCharacterSets = self.ui.findChild(QMenu, "menuCharacter_Sets")
        self.actionAboutApp = self.ui.findChild(QAction, "actionAbout_Cute_Edit")
        self.actionAboutQt = self.ui.findChild(QAction, "actionAbout_Qt")
        self.plainTextNow = self.ui.findChild(QTextEdit, "textEdit")
        self.menuEncoding = self.ui.findChild(QMenu, "menuEncoding")
        self.actionSystem = self.ui.findChild(QAction, "actionSystem")
        self.actionUtf8 = self.ui.findChild(QAction, "actionUTF_8")
        self.actionUtf8Bom = self.ui.findChild(QAction, "actionUTF_8_BOM")
        self.actionUtf16Le = self.ui.findChild(QAction, "actionUTF_16_LE_BOM")
        self.actionUtf16Be = self.ui.findChild(QAction, "actionUTF_16_BE_BOM")
        self.actionClose = self.ui.findChild(QAction, "actionClose")
        self.actionAwaysOnTop = self.ui.findChild(QAction, "actionAways_on_Top")

        self.actionFind = self.ui.findChild(QAction, "actionFind")
        self.actionFindInFile = self.ui.findChild(QAction, "actionFind_in_File")
        self.actionFindNext = self.ui.findChild(QAction, "actionFind_Next")
        self.actionFindPrevious = self.ui.findChild(QAction, "actionFind_Previous")

        self.actionToolBar = self.ui.findChild(QAction, "actionTool_Bar")
        self.actionStatusBar = self.ui.findChild(QAction, "actionStatus_Bar")
        self.actionTabBar = self.ui.findChild(QAction, "actionTab_Bar")

        self.actionPreferences = self.ui.findChild(QAction, "actionPreferences")

        self.menuPlugins = self.ui.findChild(QMenu, "menuPlugins")
        self.actionPluginMgr = self.ui.findChild(QAction, "actionPlugin_Mgr")


        settings = QSettings("Xairy", "CuteEdit")
        settings.beginGroup("View")

        staysOnTop = False
        staysOnTopVar = settings.value("staysOnTop")
        if staysOnTopVar != None:
            staysOnTop = staysOnTopVar == "true"
            self.actionAwaysOnTop.setChecked(staysOnTop)

        toolBarVisible = True
        toolBarVisibleVar = settings.value("toolBarVisible")
        if toolBarVisibleVar != None:
            toolBarVisible = toolBarVisibleVar == "true"
            self.actionToolBar.setChecked(toolBarVisible)

        statusBarVisible = True
        statusBarVisibleVar = settings.value("statusBarVisible")
        if statusBarVisibleVar != None:
            statusBarVisible = statusBarVisibleVar == "true"
            self.actionStatusBar.setChecked(statusBarVisible)

        tabBarVisible = True
        tabBarVisibleVar = settings.value("tabBarVisible")
        if tabBarVisibleVar != None:
            tabBarVisible = tabBarVisibleVar == "true"
            self.actionTabBar.setChecked(tabBarVisible)

        self.toolBarVisible(toolBarVisible)
        self.statusBarVisible(statusBarVisible)
        self.tabBarVisible(tabBarVisible)
        self.staysOnTop(staysOnTop)


        self.connectSlots()
        self.initCodecs()
        
        self.createNewTab()
        self.updateCurrentTitle()

    def openCommandFiles(self, files):
        for file in files:
            if QFileInfo(file).exists():
                self.openFileByName(file)

    def eventFilter(self, obj, event):
        if obj == self.ui and event.type() == QEvent.Close:
            for i in range(0, self.mainTab.count()):
                widget = self.mainTab.widget(i)
                info = self.tabWidgets[widget]
                if info.textEdit.document().isModified():
                    self.mainTab.setCurrentWidget(widget)
                    ret = QMessageBox.question(self.ui, "Save", "Save file '" + info.file + "'", QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel)
                    if ret == QMessageBox.Yes:
                        self.saveCurrentFile()
                    elif ret == QMessageBox.No:
                        pass
                    else:
                        event.ignore()
                        return True

            qApp.exit(0)
            return True
        elif event.type() == QEvent.Drop and isinstance(obj.parentWidget(), TextEdit):
            if event.mimeData() == None:
                return False
            if event.mimeData().hasText():
                if len(event.mimeData().urls()) >= 0:
                    #如果隐藏了tabBar, 只同时打开一个文件
                    if not self.actionTabBar.isChecked():
                        self.closeCurrentTab()
                    fileName = event.mimeData().urls()[0].toLocalFile()
                    if self.mainTab.count() == 0:
                        self.openFileByName(fileName)
                    else:
                        for i in range(0, self.mainTab.count()):
                            widget = self.mainTab.widget(i)
                            info = self.tabWidgets[widget]
                            if QFileInfo(info.file) == QFileInfo(fileName):
                                self.mainTab.setCurrentWidget(widget)
                                return True
                        self.openFileByName(fileName)

                return True
            else:
                return True
        return False

    def connectSlots(self):
        import sys        
        self.actionOpen.triggered.connect(self.openFile)
        self.actionAboutQt.triggered.connect(lambda:QApplication.aboutQt())
        self.actionAboutApp.triggered.connect(lambda:(QMessageBox.information(self.ui, "About", "Version: " + MainAppUI.version + "                ")))
        self.actionExit.triggered.connect(lambda:qApp.exit())

        self.mainTab.tabCloseRequested.connect(self.tabCloseRequested)
        self.mainTab.currentChanged.connect(self.tabChanged)
        self.actionNew.triggered.connect(self.createNewFile)
        self.actionClose.triggered.connect(self.closeCurrentTab)
        self.actionSave.triggered.connect(self.saveCurrentFile)
        self.actionSaveAll.triggered.connect(self.saveAllFile)
        self.actionCloseAll.triggered.connect(self.closeAllFile)
        self.actionUpdate.triggered.connect(self.updateCurrentFile)

        self.actionCopy.triggered.connect(self.editCopy)
        self.actionCut.triggered.connect(self.editCut)
        self.actionPaste.triggered.connect(self.editPaste)
        self.actionDelete.triggered.connect(self.editDelete)
        self.actionSelectAll.triggered.connect(self.editSelectAll)

        self.actionAwaysOnTop.triggered.connect(self.staysOnTop)

        self.actionFind.triggered.connect(lambda:self.findui.show(0))
        self.actionFindInFile.triggered.connect(lambda:self.findui.show(2))
        self.actionFindNext.triggered.connect(lambda:self.findui.findNext)
        self.actionFindPrevious.triggered.connect(lambda:self.findui.findPrevious)

        self.actionToolBar.triggered.connect(self.toolBarVisible)
        self.actionStatusBar.triggered.connect(self.statusBarVisible)
        self.actionTabBar.triggered.connect(self.tabBarVisible)

        self.actionPreferences.triggered.connect(lambda:self.prefrencesui.show())

        self.actionPluginMgr.triggered.connect(lambda:self.pluginmgrui.show())

    def initCodecs(self):
        codecs = QTextCodec.availableCodecs()

        codecsText = []
        for codecOne in codecs:
            codecsText.append(str(codecOne.data(), encoding="utf-8"))
        codecsText.sort()

        existCodecsText = [u"UTF-16LE", u"UTF-16BE", u"UTF-8", u"System"]
        for existText in existCodecsText:
            if existText in codecsText:
                index = codecsText.index(existText)
                codecsText.pop(index)
        self.actionGroup = QActionGroup(self.ui)
        for codecOne in codecsText:
            action = self.menuCharacterSets.addAction(codecOne)
            action.setObjectName(codecOne)
            action.setCheckable(True)
            self.actionGroup.addAction(action)

        self.actionGroup.addAction(self.actionSystem)
        self.actionSystem.setObjectName(u"System")
        self.actionGroup.addAction(self.actionUtf8)
        self.actionUtf8.setObjectName(u"UTF-8")
        self.actionGroup.addAction(self.actionUtf8Bom)
        self.actionUtf8Bom.setObjectName(u"UTF-8BOM")
        self.actionGroup.addAction(self.actionUtf16Le)
        self.actionUtf16Le.setObjectName(u"UTF-16LE")
        self.actionGroup.addAction(self.actionUtf16Be)
        self.actionUtf16Be.setObjectName(u"UTF-16BE")
        
        self.actionGroup.triggered.connect(self.changeCurrentCodec);

    def saveCurrentFile(self):
        currentWidget = self.mainTab.currentWidget()
        if not currentWidget in self.tabWidgets:
            return;
        index = self.mainTab.currentIndex()
        tabFile = self.mainTab.tabText(index)
        info = self.tabWidgets[currentWidget]
        if info.file == tabFile:
            homePath = QDir.homePath()
            homePath = homePath + "/" + info.file
            saveName = QFileDialog.getSaveFileName(self.ui, u"Save File", homePath, u"All types(*.);;Text file(*.txt)", u"Text file(*.txt)")
            if saveName[0] == "" or saveName[1] == "":
                return
            info.file = saveName[0]

        file = QFile(info.file)
        file.open(QIODevice.WriteOnly);
        stream = QTextStream(file);
        codecNow = info.codec
        if codecNow.find("BOM") != -1:
            codecNow = codecNow.replace("BOM", "")
            stream.setGenerateByteOrderMark(True)
        if codecNow.find("BE") != -1 or codecNow.find("LE") != -1:
            stream.setGenerateByteOrderMark(True)

        print("save file to :" + info.file + " by code:" + codecNow)
        stream.setCodec(codecNow)
        stream << currentWidget.toPlainText()
        file.close()
        info.textEdit.document().setModified(False)

    def saveAllFile(self):
        for i in range(0, self.mainTab.count()):
            widget = self.mainTab.widget(i)
            info = self.tabWidgets[widget]
            if info.textEdit.document().isModified():
                self.mainTab.setCurrentWidget(widget)
                self.saveCurrentFile()

    def closeAllFile(self):
        totalTabCount = self.mainTab.count()
        for i in range(0, totalTabCount):
            widget = self.mainTab.widget(0)
            self.mainTab.setCurrentWidget(widget)
            self.closeCurrentTab()

    def updateCurrentFile(self):
        editWidget = self.mainTab.currentWidget()
        if editWidget in self.tabWidgets:
            tabInfo = self.tabWidgets[editWidget]
            self.openFileByName(tabInfo.file, True)

    def changeCurrentCodec(self, action):
        currentWidget = self.mainTab.currentWidget()
        if not currentWidget in self.tabWidgets:
            return;
        index = self.mainTab.currentIndex()
        info = self.tabWidgets[currentWidget]
        if info.codec == action.objectName():
            return
        info.codec = action.objectName()

        file = QFile(info.file)
        if not file.exists():
            return
        file.open(QIODevice.ReadOnly);
        stream = QTextStream(file);
        stream.setCodec(info.codec)
        newContent = stream.readAll()
        currentWidget.setText(newContent)

    def closeCurrentTab(self):
        index = self.mainTab.currentIndex()
        self.tabCloseRequested(index)

    def tabChanged(self, index):
        widgetCurrent = self.mainTab.widget(index)
        if widgetCurrent in self.tabWidgets:
            tabInfo = self.tabWidgets[widgetCurrent]
            codec = tabInfo.codec
            self.setCurrentFileCodec(codec)
        else:
            self.setCurrentFileCodec()

        self.updateCurrentTitle()

    def createNewFile(self):
        textEdit = self.createNewTab()        
        self.mainTab.setCurrentWidget(textEdit)
        self.updateCurrentTitle()

    def staysOnTop(self, isTop):
        if isTop:
            self.ui.setWindowFlags(self.ui.windowFlags() | Qt.WindowType.WindowStaysOnTopHint)
        else:
            self.ui.setWindowFlags(self.ui.windowFlags() & ~Qt.WindowType.WindowStaysOnTopHint)

        settings = QSettings("Xairy", "CuteEdit")
        settings.beginGroup("View")
        settings.setValue("staysOnTop", isTop)
        settings.endGroup()
        settings.sync()

        self.ui.show()

    def toolBarVisible(self, visible):
        settings = QSettings("Xairy", "CuteEdit")
        settings.beginGroup("View")
        settings.setValue("toolBarVisible", visible)
        settings.endGroup()
        settings.sync()
        self.toolBar.setVisible(visible)

    def statusBarVisible(self, visible):
        settings = QSettings("Xairy", "CuteEdit")
        settings.beginGroup("View")
        settings.setValue("statusBarVisible", visible)
        settings.endGroup()
        settings.sync()
        self.statusbar.setVisible(visible)

    def tabBarVisible(self, visible):
        settings = QSettings("Xairy", "CuteEdit")
        settings.beginGroup("View")
        settings.setValue("tabBarVisible", visible)
        settings.endGroup()
        settings.sync()
        self.mainTab.tabBar().setVisible(visible)

    def editCopy(self):
        textEdit = self.mainTab.currentWidget()
        textEdit.copy()

    def editCut(self):
        textEdit = self.mainTab.currentWidget()
        textEdit.cut()

    def editPaste(self):
        textEdit = self.mainTab.currentWidget()
        textEdit.paste()

    def editDelete(self):
        textEdit = self.mainTab.currentWidget()
        actions = textEdit.createStandardContextMenu().actions()
        for i in range(0, len(actions)):
            if actions[i].objectName() == "edit-delete":
                actions[i].trigger()
                return

    def editSelectAll(self):
        textEdit = self.mainTab.currentWidget()
        textEdit.selectAll()

    def tabCloseRequested(self, index):
        textEdit = self.mainTab.widget(index)

        if self.mainTab.count() == 1:
            if textEdit in self.tabWidgets:
                if textEdit.document().isModified():
                    tabInfo = self.tabWidgets[textEdit]
                    ret = QMessageBox.question(self.ui, "Save", "Save file '" + tabInfo.file + "'", QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel)
                    if ret == QMessageBox.Yes:
                        self.saveCurrentFile()
                    elif ret == QMessageBox.No:
                        pass
                    else:
                        return
                self.tabWidgets.pop(textEdit)
            self.mainTab.removeTab(index)

            self.createNewTab()
            self.updateCurrentTitle()
            return


        if textEdit in self.tabWidgets:
            tabInfo = self.tabWidgets[textEdit]
            if textEdit.document().isModified():
                tabInfo = self.tabWidgets[textEdit]
                ret = QMessageBox.question(self.ui, "Save", "Save file '" + tabInfo.file + "'", QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel)
                if ret == QMessageBox.Yes:
                    self.saveCurrentFile()
                elif ret == QMessageBox.No:
                    pass
                else:
                    return
            self.tabWidgets.pop(textEdit)
        self.mainTab.removeTab(index)
        self.updateCurrentTitle()

    def checkTextEncoding(self, file):
        #找了一段各种字符的字符串, 转换成对应的编码, 看下能识别的字符数量, 数量多的被定义为可以解码.

        self.original = u"这是一段中亠︼﹄﹂ˉ︾︺﹀︸︶︵︷︿︹︽_﹁﹃︻】【」「}{〕〔》《］［（）〈〉‹›﹛﹜『』〖〗㈠㈡㈢㈣㈤㈥㈦㈧㈨㈩ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩ❶❷❸❹❺❻❼❽❾❿①②③④⑤⑥⑦⑧⑨⑩⑳⑲⑱⑰⑯⑮⑭⑬⑫⑪⒈⒉⒊⒋⒌⒍⒎⒏⒐⒑½⅓⅔¼¾⅛⅜⅝⅞∴∵∷ΝΞΟΠΡΣΤΥΦΧΨΩㄅㄆㄇㄈㄉㄊㄋㄌㄍㄎㄏㄐāáǎàōóǒò衤罒覀夂癶耂牜虍歺糹釒飠㈈㈉㈊㈋㈌㈍㈎㈏㈐㈑㈒㈓ㅱㅲㅳㅴㅵㅶㅷㅸㅹㅺㅻㅼi:ə:a:ɔ:u:ieæəʌɔuあいうえおかきくけこさしユヨラリルレロワヲン゛゜┞┟┠┡┢┦┧┨┩┪╉╊✈✁〠〄♝♞◕†‡¬￢✌㏠㏡㏢㏣㏤㏥㏦㏧㏨㏩㏪㏫ⓐⓑⓒⓓⓔⓕⓖⓗⓘⓙⓚⓛ"
        if file.size() < len(self.original):
            return u"UTF-8"
        
        codecUtf8 = QTextCodec.codecForName("utf-8")
        bytesOriginal = codecUtf8.fromUnicode(self.original);
        codecs = QTextCodec.availableCodecs()
        codecs.remove(QByteArray(b"System"))
        if len(self.codecInfo) == 0:            
            for codecOne in codecs:
                codec = QTextCodec.codecForName(codecOne)
                state = QTextCodec.ConverterState()
                bytesDecoded = codec.fromUnicode(self.original)
                textRecoded = codec.toUnicode(bytesDecoded)

                sameCount = 0
                loopStep = len(self.original) if len(self.original) < len(textRecoded) else len(textRecoded)
                for i in range(0, loopStep):
                    if self.original[i] == textRecoded[i]:
                        sameCount = sameCount + 1
                self.codecInfo[codecOne] = sameCount
        sample = file.read(bytesOriginal.size())
        file.seek(0)
        validCodecs = dict()
        containsSystem = False
        for codecOne in codecs:
            #print(str(codecOne.data(), encoding="utf-8"))
            codec = QTextCodec.codecForName(codecOne)
            stream = QTextStream(sample)
            stream.setCodec(codec)
            codedStr1 = stream.read(100)
            converted = codec.fromUnicode(codedStr1)
            lenconv = converted.size()
            readed = sample.mid(0, lenconv)
            state = QTextCodec.ConverterState()
            codedStr2 = codec.toUnicode(readed)

            if converted == readed and codedStr1 == codedStr2:
                sameCount = self.codecInfo[codecOne]
                validCodecs.setdefault(sameCount, []).append(codecOne)
                if codecOne.toLower() == QByteArray(b"system"):
                    containsSystem = True
                continue

        keys = list(validCodecs.keys())
        keys.sort()
        indexKey = len(keys);
        if indexKey == 0:
            return u"system"
        dictKey1 = keys[indexKey - 1]
        dictKey2 =  0
        if indexKey - 2 >= 0:
            dictKey2 = keys[indexKey - 2]
        if dictKey2 < len(self.original) / 5:
            dictValue = validCodecs[dictKey1]
        else:
            dictValue = validCodecs[dictKey2]

        return str(dictValue[0].data(), encoding="utf-8")

    def createNewTab(self, tabFile = "new file "):

        #打开一个文件的时候,只有一个标签页, 并且这个标签页没有修改过, 也没有存文件, 就替换它.
        if self.mainTab.count() == 1 and tabFile != "new file ":
            textEdit = self.mainTab.widget(0)
            if not QFileInfo(self.tabWidgets[textEdit].file).exists() and textEdit.document().characterCount() == 1:
                self.mainTab.removeTab(0)
                self.tabWidgets.pop(textEdit)

        #如果不显示tabbar的情况下, 只会有一个标签
        if not self.actionTabBar.isChecked() and len(self.tabWidgets) > 0:
            self.tabWidgets = {}
            self.mainTab.clear()

        if tabFile == "new file ":
            tabNames = []
            for i in range(0, self.mainTab.count()):
                tabName = self.mainTab.tabText(i)
                newFileStr = "new file "
                indexNewFile = tabName.find(newFileStr)
                if indexNewFile == 0:
                    pureNumberStr = tabName[len(newFileStr):]
                    indexText = pureNumberStr.find(".")
                    if indexText != -1:
                        pureNumberStr = pureNumberStr[0:indexText]
                    print(pureNumberStr)
                    if pureNumberStr != "":
                        tabNames.append(int(pureNumberStr))
            
            for i in range(1, 0xFFFF):
                if i not in tabNames:
                    tabFile = tabFile + str(i)
                    break;

        textEdit = TextEdit()
        fileName = QFileInfo(tabFile).fileName()
        self.mainTab.addTab(textEdit, fileName)
        tabInfo = TabWidgetInfo()
        tabInfo.file = tabFile
        tabInfo.codec = u"UTF-8"
        tabInfo.textEdit = textEdit
        self.actionUtf8.setChecked(True)

        self.tabWidgets[textEdit] = tabInfo

        textEdit.document().modificationChanged.connect(self.documentContentChanged)
        textEdit.viewport().installEventFilter(self)
        return textEdit

    def documentContentChanged(self, changed):
        document = self.sender()
        editWidget = self.mainTab.currentWidget()
        for i in range(0, self.mainTab.count()):
            widget = self.mainTab.widget(i)
            if editWidget != widget:
                continue

            info = self.tabWidgets[widget]
            if info.textEdit.document() == document:
                self.updateCurrentTitle()

    def setCurrentFileCodec(self, codecName = u"System"):   
        actions = self.actionGroup.actions()
        for action in actions:
            if action.text() == codecName:
                action.setChecked(True)

    def openFile(self):
        dialogRet = QFileDialog.getOpenFileName(self.ui, "Open File", ".", "All types(*.*);;Text Files (*.txt)")
        if dialogRet == None or dialogRet[0] == "":
            return
        fileName = dialogRet[0]
        self.openFileByName(fileName)

    def openFileByName(self, fileName, reload = False):
        textEdit = None
        for i in range(0, self.mainTab.count()):
            widget = self.mainTab.widget(i)
            info = self.tabWidgets[widget]
            if QFileInfo(info.file) == QFileInfo(fileName):
                if reload:
                    textEdit = info.textEdit
                else:
                    return

        file = QFile(fileName)
        if not file.open(QIODevice.ReadOnly):
            return
        codecName = self.checkTextEncoding(file)
        print("code:" + codecName)
        stream = QTextStream(file)
        if codecName != "":
            stream.setCodec(codecName)
        content = stream.readAll();

        if textEdit == None:
            textEdit = self.createNewTab(fileName)

        textCursor = textEdit.textCursor()
        lastIndex = textCursor.position()
        textEdit.setText(content)

        if reload:
            textCursor = textEdit.textCursor()
            if lastIndex < textEdit.document().characterCount():
                textCursor.setPosition(lastIndex)
                textEdit.setTextCursor(textCursor)

        self.mainTab.setCurrentWidget(textEdit)
        self.tabWidgets[textEdit].codec = codecName
        self.setCurrentFileCodec(codecName)

        self.updateCurrentTitle()

    def updateCurrentTitle(self):
        editWidget = self.mainTab.currentWidget()
        if editWidget in self.tabWidgets:
            tabInfo = self.tabWidgets[editWidget]
            strChanged = ""
            if tabInfo.textEdit.document().isModified():
                strChanged = "* "
            self.ui.setWindowTitle(strChanged + tabInfo.file + " - Cute Edit")




